<template>
  <div class="doc-upload">
    <el-upload
      v-loading="docLoading"
      ref="elUpload"
      accept=".xls,.xlsx,.pdf,.docx,.pptx"
      :action="importUrl"
      :limit="maxCount"
      :file-list="fileList"
      :headers="{ Authorization: token }"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-error="handleError"
      :on-exceed="handleExceed"
    >
      <el-button type="primary">附件上传</el-button>
    </el-upload>
  </div>
</template>
<script>
import { uploadUrl } from '@/api/material';
import { uploadBaseURL } from '@/api/request.js';
import { replaceUrl } from '@/utils/utils';

export default {
  name: 'FileUpload',
  props: {
    // 图片属性数组
    modelValue: String,
    // 最大上传图片数量
    maxCount: {
      type: Number,
      default: 1,
    },
    tips: {
      type: Array,
      default() {
        return ['大小：不超过10M'];
      },
    },
  },
  emits: ['success'],
  data() {
    return {
      importUrl: `${uploadBaseURL}${replaceUrl(uploadUrl)}`,
      file: {},
      fileList: [],
      docLoading: false,
    };
  },
  computed: {
    token() {
      return this.$store.state.common.token;
    },
  },
  methods: {
    emitInput(file, name) {
      this.$emit('success', file, name);
    },
    handleRemove() {
      this.fileList = [];
      this.emitInput(this.fileList);
    },
    beforeUpload(file) {
      this.docLoading = true;
      const isDocument = ['.xls', '.xlsx', '.docx', '.pdf', '.pptx'].some(suffix => file.name.endsWith(suffix));
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isDocument) {
        this.docLoading = false;
        this.$message.error('只能上传excel/word/pdf/ppt文件');
        return false;
      }
      if (!isLt10M) {
        this.docLoading = false;
        this.$message.error('上传文件大小不能超过 10MB!');
        return false;
      }
      this.file = file;
      return true;
    },
    handleUploadSuccess(res) {
      if (res.code === 401) {
        this.$router.push({
          path: '/login',
          query: {
            to: this.$route.path,
          },
        });
        return;
      }
      if (res.code !== 200) {
        this.$message.error(res.msg);
        this.docLoading = false;
        this.fileList = [];
        return;
      }
      this.docLoading = false;
      this.emitInput(res.data, this.file.name);
      this.$message.success('上传成功');
    },
    handleError(err) {
      this.$message.error(err.msg || '上传失败');
      this.docLoading = false;
      this.fileList = [];
    },
    handleExceed() {
      this.$message({
        message: `最多只能上传${this.maxCount}个文件`,
        type: 'warning',
      });
    },
  },
};
</script>
<style lang="less" scoped>
</style>
